package com.jsmy.softapp.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.view.Display;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.facade.callback.NavCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.jsmy.softapp.MyApp;
import com.jsmy.softapp.R;
import com.jsmy.softapp.adapter.SoftFragmentAdapter;
import com.jsmy.softapp.aroute.AR;
import com.jsmy.softapp.bean.LoginBean;
import com.jsmy.softapp.bean.VersionBean;
import com.jsmy.softapp.fragment.BusinessFragment;
import com.jsmy.softapp.fragment.DailyFragment;
import com.jsmy.softapp.fragment.DataFragment;
import com.jsmy.softapp.fragment.FragmentSmanager;
import com.jsmy.softapp.fragment.HomeFragment;
import com.jsmy.softapp.fragment.PlantFragment;
import com.jsmy.softapp.net.API;
import com.jsmy.softapp.net.NetWork;
import com.jsmy.softapp.presenter.MainPresenter;
import com.jsmy.softapp.service.LocationService;
import com.jsmy.softapp.util.DialogUtils;
import com.jsmy.softapp.util.ToastUtil;
import com.jsmy.softapp.util.VersionUtil;
import com.jsmy.softapp.view.MainView;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

@Route(path = AR.A_MAIN)
public class MainActivity extends BaseActivity<MainView, MainPresenter>
        implements NavigationView.OnNavigationItemSelectedListener, MainView {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.navigation)
    BottomNavigationView navigation;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawer;

    @BindView(R.id.right)
    CoordinatorLayout right;
    @BindView(R.id.nav_view)
    NavigationView left;
    @BindView(R.id.mviewpager)
    ViewPager mViewPager;
    @BindView(R.id.img_avatar)
    CircleImageView imgAvatar;
    @BindView(R.id.tv_content)
    TextView tvContent;

    private SoftFragmentAdapter adapter;
    private boolean isDrawer = false;
    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
//                    toolbar.setTitle("首页");
                    mViewPager.setCurrentItem(0);
                    return true;
                case R.id.navigation_dashboard:
//                    toolbar.setTitle("资料");
                    mViewPager.setCurrentItem(1);
                    return true;
                case R.id.navigation_notifications:
//                    toolbar.setTitle("业务");
                    mViewPager.setCurrentItem(2);
                    return true;
            }
            return false;
        }
    };

    VersionBean.DataBean bean;
    LoginBean.DataBean info;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected MainPresenter createPresenter() {
        return new MainPresenter();
    }

    @Override
    protected void initView() {
        NetWork.setImageGlide(this, MyApp.getMyApp().bean.getIco(), imgAvatar);
        tvContent.setText(MyApp.getMyApp().bean.getTitle());
        NetWork.setImageGlide(this, MyApp.getMyApp().bean.getIco(), (CircleImageView) left.getHeaderView(0).findViewById(R.id.img_avatar));
        ((TextView) left.getHeaderView(0).findViewById(R.id.tv_name)).setText("金牌：" + MyApp.getMyApp().bean.getUsername());
        ((TextView) left.getHeaderView(0).findViewById(R.id.tv_content)).setText(MyApp.getMyApp().bean.getTitle());

        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

        left.getMenu().getItem(0).setTitle(MyApp.getMyApp().bean.getDkzt());


//        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
//                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
//        drawer.addDrawerListener(toggle);
//        toggle.syncState();

        left.setNavigationItemSelectedListener(this);
        left.getHeaderView(0).findViewById(R.id.img_avatar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ARouter.getInstance().build(AR.A_MINE).navigation(MainActivity.this, new NavCallback() {
                    @Override
                    public void onArrival(Postcard postcard) {
                        drawer.closeDrawer(GravityCompat.START);
                    }
                });
            }
        });
        right.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (isDrawer) {
                    return left.dispatchTouchEvent(motionEvent);
                } else {
                    return false;
                }
            }
        });
        drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                isDrawer = true;
                //获取屏幕的宽高
                WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
                Display display = manager.getDefaultDisplay();
                //设置右面的布局位置  根据左面菜单的right作为右面布局的left   左面的right+屏幕的宽度（或者right的宽度这里是相等的）为右面布局的right
                right.layout(left.getRight(), 0, left.getRight() + display.getWidth(), display.getHeight());
            }

            @Override
            public void onDrawerOpened(View drawerView) {

            }

            @Override
            public void onDrawerClosed(View drawerView) {
                isDrawer = false;
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });

        adapter = new SoftFragmentAdapter(getSupportFragmentManager());
        mViewPager.setOffscreenPageLimit(3);
        mViewPager.setAdapter(adapter);
        mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        navigation.setSelectedItemId(R.id.navigation_home);
                        break;
                    case 1:
                        navigation.setSelectedItemId(R.id.navigation_dashboard);
                        break;
                    case 2:
                        navigation.setSelectedItemId(R.id.navigation_notifications);
                        break;
                }
                super.onPageSelected(position);
            }
        });

        Intent intent = new Intent(this, LocationService.class);
        intent.setClass(this, LocationService.class);
        startService(intent);
    }

    @Override
    protected void initData() {
        presenter.getversioninfo();
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        if (id == R.id.nav_sign) {
            presenter.saveqdinfo();
        } else if (id == R.id.nav_card) {
            ARouter.getInstance().build(AR.A_SHARE)
                    .withString("id", "")
                    .withString("url", API.APP_CARD)
                    .withString("title", "电子名片")
                    .withString("note", "")
                    .withString("share", "N")
                    .navigation();
            ;
        } else if (id == R.id.nav_business) {
            ARouter.getInstance().build(AR.A_SHARE)
                    .withString("id", "")
                    .withString("url", API.APP_BUSI)
                    .withString("title", "业务统计")
                    .withString("note", "")
                    .withString("share", "N")
                    .navigation();
        } else if (id == R.id.nav_about) {
            ARouter.getInstance().build(AR.A_SHARE)
                    .withString("id", "")
                    .withString("url", API.APP_ABOUT)
                    .withString("title", "关于我们")
                    .withString("note", "")
                    .withString("share", "N")
                    .navigation();
        } else if (id == R.id.nav_update) {
            if (VersionUtil.getVersionName(this).equals(bean.getVersionname())) {
                ToastUtil.showShort(this, "当前已是最新版本！");
            } else {
                DialogUtils.showVersionDialog(this, bean.getVersionname(), bean.getVermsg(), bean.getVersionurl());
            }
        } else if (id == R.id.nav_setting) {
            ARouter.getInstance().build(AR.A_SETTING).navigation();
        }

        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showLoadingData(String type, Object object) {
        switch (type) {
            case API.APP_VERSION_INFO:
                bean = ((VersionBean) object).getData();
                break;
            case API.APP_BASIC_INFO:
                info = ((LoginBean) object).getData();
                tvContent.setText(info.getTitle());
                left.getMenu().getItem(0).setTitle(info.getDkzt());
                break;
            case API.APP_SAVE_QD_INFO:
                ToastUtil.showShort(MyApp.getMyApp(),"打卡成功！");
                presenter.getbasicinfo();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        presenter.model.disposable.clear();
        Intent intent = new Intent(this, LocationService.class);
        intent.setClass(this, LocationService.class);
        stopService(intent);
        super.onDestroy();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ((PlantFragment) FragmentSmanager.getInstance().getFragment(FragmentSmanager.PLANT)).updata();
        ((DailyFragment) FragmentSmanager.getInstance().getFragment(FragmentSmanager.DAILY)).updata();
    }

    @OnClick({R.id.img_avatar, R.id.img_fresh})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_avatar:
                drawer.openDrawer(GravityCompat.START);
                break;
            case R.id.img_fresh:
                presenter.getbasicinfo();
                switch (navigation.getSelectedItemId()) {
                    case R.id.navigation_home:
                        ((HomeFragment) FragmentSmanager.getInstance().getFragment(FragmentSmanager.HOME)).updata();
                        break;
                    case R.id.navigation_dashboard:
                        ((DataFragment) FragmentSmanager.getInstance().getFragment(FragmentSmanager.DATA)).updata();
                        break;
                    case R.id.navigation_notifications:
                        ((BusinessFragment) FragmentSmanager.getInstance().getFragment(FragmentSmanager.BUSINESS)).updata();
                        break;
                }
                break;
        }
    }

}
